//
//  ChatViewController.m
//  MiniWeChat
//
//  Created by ByteDance on 2025/6/26.
//

#import "ChatViewController.h"
#import "MessageBubble.h"
#import "Masonry.h"

@interface ChatViewController ()

@end

@implementation ChatViewController

- (instancetype)initWithConversation:(ConversationModel *)conversation {
    self = [self init];
    if (self) {
        self.viewModel = [[ChatViewModel alloc] initWithConversation:conversation];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.viewModel.conversation.nickname;
    
    [self setupTableView];
    [self setupInputView];
    [self setupGestureRecognizer];
    [self registerNotificationsListening];
    
    [self.viewModel fetchMessages];
    
    [self showLastestMessage];
}

- (void)setupTableView {
    CGFloat inputViewHeight = 50;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - inputViewHeight) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    // 设置行高为自动计算
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    // 隐藏默认分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [_tableView registerClass:[MessageBubble class] forCellReuseIdentifier:@"MessageBubble"];
    [self.view addSubview:_tableView];
}

- (void)setupInputView {
    self.inputView = [[WXInputView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 50, self.view.bounds.size.width, 50)];
    // 前置知识：引用计数为 0 则销毁
    // vc => inputView => sendBlock -> vc
    // 从左往右销毁 若 sendBlock => vc 则存在循环引用则无法销毁
    __weak __typeof(self)weakSelf = self;
    self.inputView.sendBlock = ^(NSString *text) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.viewModel sendMessage:text];
    };
    [self.view addSubview:self.inputView];
}

#pragma mark - 手势识别器
- (void)setupGestureRecognizer {
    // 添加点击手势识别器
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestureRecognizer:)];
    [self.tableView addGestureRecognizer:tapGestureRecognizer];
}

- (void)handleTapGestureRecognizer:(UITapGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateEnded) {
        [self.inputView.textView resignFirstResponder];
    }
}

- (void)registerNotificationsListening {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(messagesUpdated:)
                                                 name:kNotificationMessagesUpdated
                                               object:nil];
}

- (void)messagesUpdated:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        [self showLastestMessage];
    });
}

- (void)showLastestMessage {
    if (![self.viewModel numberOfMessages]) return;
    // 获取最后一节的最后一行的索引路径
    NSInteger section = [self.tableView numberOfSections] - 1;
    NSInteger row = [self.tableView numberOfRowsInSection:section] - 1;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
    // 滚动到最后一行 UITableViewScrollPositionBottom 表示滚动到该行底部显示
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}


#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"「聊天页」加载 %ld 条消息", [self.viewModel numberOfMessages]);
    return [self.viewModel numberOfMessages];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageBubble *messageBubble = [tableView dequeueReusableCellWithIdentifier:@"MessageBubble" forIndexPath:indexPath];
    MessageModel *message = [self.viewModel messageAtIndex:indexPath.row];
    [messageBubble setMessage:message];
    return messageBubble;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kNotificationMessagesUpdated
                                                  object:nil];
}

@end
